<?php

namespace App\Admin\Forms\User;

use App\Admin\Utils\DownUtils;
use App\Models\User\WxUserInviteTempCode;
use App\Models\WxTenant;
use App\Wen\Utils\Settings;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class UserInviteTepCodeBatchForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {
        $type = $input['type'];
        if(!in_array($type, [1, 2])){
            $type = 1;
        }
        $path = $input['path'];
        $tenant_id = (int)_empty_default_($input['tenant_id'], 0);
        $num = (int)_empty_default_($input['num'], 1);
        $zip_down = _empty_default_($input['zip_down'], 0) == 1 ? 1 : 0;
        $with_bg = _empty_default_($input['with_bg'], 0) == 1 ? 1 : 0;

        $temp_code_bg = [];
        if($with_bg){
            $temp_code_bg = Settings::get('app_user_invite_temp_code_bg', []);
            if(_empty_($temp_code_bg)){
                return $this->response()->warning('你还没有配置背景图');
            }
        }


        $ids = [];
        for ($i = 0; $i < $num; $i++){
            $model = new WxUserInviteTempCode();
            $model->type = $type;
            if($path){
                $model->path = $path;
            }
            if($tenant_id >= 0){
                $model->tenant_id = $tenant_id;
            }
            $model->status = 0;
            $model->save();
            $ids[] = $model->id;
        }

        if($zip_down == 1){
            $codes = WxUserInviteTempCode::whereIn('id', $ids)
                ->get(['id', 'code'])
                ->map(function ($item) {
                    return [
                        'name' => 'id-'.$item->id,
                        'url' => $item->code
                    ];
                })->toArray();
            if($codes){
                if($with_bg){
                    $zip_file_path = DownUtils::down_invite_temp_code_with_bg($codes, $temp_code_bg[0]);
                    return $this->response()->download($zip_file_path);
                }else{
                    $zip_file_path = DownUtils::down_invite_temp_code($codes);
                    return $this->response()->download($zip_file_path);
                }
            }else{
                return $this->response()->error('下载程序出错');
            }
        }else{
            return $this->response()->refresh()->success('操作成功');
        }
    }

    public function form()
    {
        $this->radio('type')->options([1=>'传单', 2=>'桌牌'])->default(1);
        $this->text('path')->default('/pages/tabbar/index/index');
        $this->select('tenant_id')->options(WxTenant::orderBy('order', 'desc')->orderBy('tenant_id')->pluck('name', 'tenant_id'));
        $this->number('num', '数量')->max(50)->default(1);
        $this->switch('zip_down','下载')->default(1);
        $this->switch('with_bg','带背景')->default(1);
    }
}
